import { create } from 'zustand'
import Layout from '@/layout'
import { Suspense, lazy } from 'react'
import { Outlet } from 'react-router-dom'
import { getUserMenuAuthApi } from '@/api/user'

type MenuStoreType = {
  menu: Menu[]
  setMenu: () => Promise<void>
  getMenu: () => Menu[]
  defaultKey: string
  setDefaultKey: (key: string) => void
  getDefaultKey: () => string
  keyMap: Record<string, MenuType>
  getKeyMap: () => Record<string, MenuType>
}
interface MenuType {
  id: string
  parentId?: string
  menuType: number
  path: string
  title: string
  routeName: string
  icon?: string
  component: string
  perms?: string
  sort?: number
  children?: MenuType[]
  [key: string]: any
}
interface Menu {
  path: string
  label: string
  key: string
  element: JSX.Element
  children?: Menu[]
}

const modules = import.meta.glob('@/pages/**/*.tsx') as Record<
  string,
  () => Promise<{ default: React.ComponentType<any> }>
>

const loadComponent = (componentPath: string) => {
  const modulePath = `/src/pages${componentPath}.tsx`
  if (!modules[modulePath]) {
    return () => <div>页面菜单未找到</div>
  }
  return lazy(() => modules[modulePath]())
}

// 获取首个路径放在defaultKey中
const getRouteDefaultPath = routeItem => {
  const paths = []
  function getPathList(routeItem, pathList) {
    pathList.push(routeItem.path)
    if (routeItem?.children?.length > 0) {
      getPathList(routeItem.children[0], pathList)
    }
  }
  getPathList(routeItem, paths)
  return paths.join('/')
}

// 将后台菜单数据转换为路由配置与菜单数据,同时获取keyMap
const formatRouteList = (data: MenuType[], keyMap = {}, path = '') => {
  return (
    data?.map(item => {
      let element = <>路由加载异常...</>
      switch (item.component) {
        case 'Layout': {
          element = <Layout />
          break
        }
        case 'RouterView': {
          element = <Outlet />
          break
        }
        default:
          const ItemComp = loadComponent(item.component)
          element = (
            <Suspense>
              <ItemComp />
            </Suspense>
          )
          break
      }
      const key = path === '' ? item.path : path + '/' + item.path
      keyMap[key] = item
      return {
        path: item.path,
        label: item.title,
        key,
        element,
        children: item.children ? formatRouteList(item.children, keyMap, key) : null
      }
    }) ?? []
  )
}

const useMenu = create<MenuStoreType>((set, get) => ({
  menu: [],
  setMenu: async () => {
    try {
      const { code, data } = await getUserMenuAuthApi()
      if (code === 0) {
        let keyMap = {}
        const menuData = formatRouteList(data ?? [], keyMap)

        set({ menu: menuData, keyMap, defaultKey: getRouteDefaultPath(menuData?.[0]) })
      }
    } catch (error) {
      set({ menu: [] })
    }
  },
  getMenu: () => {
    return get().menu
  },
  defaultKey: '',
  setDefaultKey(key) {
    set({ defaultKey: key ?? '' })
  },
  getDefaultKey() {
    return get().defaultKey
  },
  keyMap: {},
  getKeyMap() {
    return get().keyMap
  }
}))

// 获取面包屑功能需要的数据结构
const getBreadcrumbList = (key: string, keyMap: Record<string, MenuType>) => {
  const keyList = key?.split('/') ?? []

  let pathKey = '',
    list = []
  for (let i = 1; i < keyList.length; i++) {
    let currentKey = pathKey + '/' + keyList[i]
    keyMap[currentKey] &&
      list.push({
        title: keyMap[currentKey].title,
        key: currentKey
      })
    pathKey = currentKey
  }

  return list
}
// 获取重定向的路由
const getRedirectRoute = (path: string, routeItem: MenuType): string => {
  try {
    const defaultRoute = getRouteDefaultPath(routeItem)
    if (defaultRoute.startsWith(path)) {
      return defaultRoute
    }
    const defaultRouteList = defaultRoute.split('/')

    if (path.endsWith(defaultRouteList[0])) {
      return path + '/' + defaultRouteList.slice(1).join('/')
    }
  } catch (error) {
    return '/'
  }
}

export {
  useMenu,
  MenuType,
  formatRouteList,
  getRouteDefaultPath,
  getBreadcrumbList,
  getRedirectRoute
}
